// SEE END OF FILE FOR LICENSE TERMS

#include "defines.h"
#include "interfaceOptions.h"
#include "heartbeat.h"

volatile unsigned int tickCount = 0;

unsigned int getHeartbeatTick(void)
{
	return tickCount;
}

//  process T3 interrupt
// Timer 3 is used to find the end of receiver frame.
// Any received servo PWM signal will reset this timer
// When a full frame has been received, T3 is triggered before the timer finishes.
// During normal operation, this interrupt should never happen due to timeout.
void __attribute__((__interrupt__,__no_auto_psv__)) _T3Interrupt(void) 
{
	interrupt_save_extended_state ;
	indicate_loading_inter ;

//	LATFbits.LATF1 = !(LATFbits.LATF1);

	tickCount++;

// 	T3CONbits.TON = 0 ;			// turn off timer 3, only happens once per frame
//	TMR3 = 0;

	radio_heartbeat_callback(tickCount);
	
	IFS0bits.T3IF = 0 ;			// clear the interrupt
	
	interrupt_restore_extended_state ;
	return ;
}

void init_heartbeat(void)
{
	// Timer 3 is used to measure time spent per second in interrupt routines
	// which enables the calculation of the CPU loading.
	TMR3 = 0 ;					// initialize timer'
	PR3	= HEARTBEAT_PERIOD;		// Set frame timeout time
	T3CONbits.TCKPS = 2 ;		// prescaler = 64 option
	T3CONbits.TCS = 0 ;	    	// use the XTAL/PLL to drive the clock
	IEC0bits.T3IE = 1 ;			// enable the interrupt
	T3CONbits.TON = 1 ;			// turn on timer 3

//	TRISFbits.TRISF1 = 0; 	// Set CAN1 TX to output
}


/****************************************************************************/
// This is part of the servo and radio interface software
//
// ServoInterface source code
//	http://code.google.com/p/rc-servo-interface
//
// Copyright 2010 ServoInterface Team
// See the AUTHORS.TXT file for a list of authors of ServoInterface.
//
// ServoInterface is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// ServoInterface is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License 
// along with ServoInterface.  If not, see <http://www.gnu.org/licenses/>.
//
// Many parts of ServoInterface use either modified or unmodified code
// from the MatrixPilot pilot project.
// The project also contains code for modifying MatrixPilot to operate
// with ServoInterface.
// For details, credits and licenses of MatrixPilot see the AUTHORS.TXT file.
// or see this website: http://code.google.com/p/gentlenav
/****************************************************************************/
